<?php
/**
* @filename source_module.php 2016-9-24 14:48:32x
* @author Wei Chai <chaizifu@163.com>
* @version 1.0.0
* @copyright DZF (c) 2016, Wei Chai
*/
class ctrl_trade_main extends trade_main{
    
    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();
    public static $field_value = array();
    
    //1.课程与内容不符 2.盗版/侵权课程 3.老师授课问题 4.课程质量问题 5.其他
    public static $reasonArr = array(
        1   =>  '课程与内容不符',
        2   =>  '盗版/侵权课程',
        3   =>  '老师授课问题',
        4   =>  '课程质量问题',
        5   =>  '其他'
    );

    //处理状态：0.待处理 1.已处理 2.已拒绝 3.已关闭
    public static $statusArr = array(
        0   =>  '',
        1   =>  '待处理',
        2   =>  '已处理',
        3   =>  '已拒绝',
        4   =>  '已关闭',
    );
    
    static function &instance() {
        static $object;
        if(empty($object)){
            $object = new self();
        }
        return $object;
    }
    
    /*
     * 单个学生所有已选课API
     */
    public function do_selected(){
        global $_G;
        $user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;//要查询的用户id
        
        $return['code'] = '1';
        $return['data'] = [];
        
        if(!$user_id){//没有传递user_id
            $return['code'] = '2';
        }
        else{//2016-12-16 14:05:52 最新文档已付款状态置为2
            $return['code'] = '0';
            
            $sql_selected = "select cm_id from ".DB::table('trade_course')." where user_id = '".$user_id."' and tc_flag = 2 and isdelete = 0 ";
            $sTmpRes = @DB::fetch_all($sql_selected);
            
            $cmArr = [];//结果集
            if(!empty($sTmpRes) && is_array($sTmpRes)){
                foreach ($sTmpRes as $item) {
                    $cmArr[$item['cm_id']] = $item['cm_id'];
                }
                
                $cmArr = array_values($cmArr);
                
                //此处课程结果集肯定不为空
                $return['data'] = @DB::fetch_all("select cm_id, cm_name, cm_img from ".DB::table('course_main')." where cm_id in ('".implode("','", $cmArr)."') ");
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 汇款订单列表API
     */
    public function do_remitlist(){
        
        global $_G;
        
        $tm_all_status = isset($_REQUEST['status']) && !empty($_REQUEST['status']) ? $_REQUEST['status'] : 0;//处理状态：1.未付款 2.已付款
        
        $so_id = isset($_REQUEST['so_id']) && !empty($_REQUEST['so_id']) ? $_REQUEST['so_id'] : 0;//网校编号
        
        $page = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : 15;
        
        $where = " and tm_way = 2 ";
        
        if($tm_all_status){
            $where.= " and tm_all_status = ".$tm_all_status;
        }
        
        if($so_id){//如果传递进来了网校编号
            $where.= " and so_id = ".$so_id;
        }
        
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = [
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $limit, //int 每页显示个数
            'wheresql' => $where, //string //条件SQL语句 
            'orderby' => " ORDER BY tm_id DESC ", //string 排序规则
        ];
        $page_result = $this->index('trade_main', $page_condition);
        
        //处理状态：1.未付款 2.已付款 
        $statusArr = array(
            1   =>  '未付款',
            2   =>  '已付款',
        );
        
        if(!empty($page_result) && is_array($page_result)){
            //此处将user_id对应换成名称
            foreach($page_result['page_data'] as $k => $item) {
                $page_result['page_data'][$k]['user_name'] = ext::user_realname($item['user_id']);
                $page_result['page_data'][$k]['status'] = $statusArr[$item['tm_all_status']];
            }
        }
        
        $return['code'] = '0';
        $return['data'] = $page_result;
        $return['data']['page_now'] = $page;
        $return['data']['total_page'] = ceil($return['data']['page_now'] / $limit);
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 待退款列表API
     */
    public function do_refundlist(){
        global $_G;
        
        $tr_status = isset($_REQUEST['status']) && !empty($_REQUEST['status']) ? $_REQUEST['status'] : 0;//处理状态：1.待处理 2.已处理 3.已拒绝 4.已关闭
        //2016-11-22
        $tr_user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;//申请人id
        $user_name = isset($_REQUEST['user_name']) && !empty($_REQUEST['user_name']) ? $_REQUEST['user_name'] : '';//申请人username
        $user_realname = isset($_REQUEST['user_realname']) && !empty($_REQUEST['user_realname']) ? $_REQUEST['user_realname'] : '';//申请人真实姓名
        $tr_id = isset($_REQUEST['tr_id']) && !empty($_REQUEST['tr_id']) ? $_REQUEST['tr_id'] : 0;//编号
        $stime = isset($_REQUEST['stime']) && !empty($_REQUEST['stime']) ? $_REQUEST['stime'] : 0;//起始时间
        $etime = isset($_REQUEST['etime']) && !empty($_REQUEST['etime']) ? $_REQUEST['etime'] : 0;//结束时间
        
        $so_id = isset($_REQUEST['so_id']) && !empty($_REQUEST['so_id']) ? $_REQUEST['so_id'] : 0;//网校编号
        
        $page = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : 15;
        
        if($tr_status){
            $where = " and tr_status = ".$tr_status;
        }
        else{
            $where = "";
        }
        
        if($tr_id){//传递进来了编号
            $where .= " and tr_id = ".$tr_id;
        }
        
        if($so_id){//传递进来了网校编号
            $where .= " and tr_so_id = ".$so_id;
        }
        
        if($stime){//传递进来了起始时间
            $where .= " and ctime >= ".$stime;
        }
        
        if($etime){//传递进来了结束时间
            $where .= " and ctime <= ".$etime;
        }
        
        if($tr_user_id){//传递进来了申请人id
            $where .= " and tr_user_id = ".$tr_user_id;
        }
        
        if($user_name){//如果传递进来了用户名的话
            //先对用户名转换成用户id
            $u_id = ext::get_user_id($user_name);
            $where .= " and tr_user_id = ".$u_id;
        }
        
        if($user_realname){//如果传递进来了用户名的话
        	//先对用户名转换成用户id
        	$u_id = ext::get_real_user_id($user_realname);
        	$where .= " and tr_user_id = ".$u_id;
        }
        
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = array(
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $limit, //int 每页显示个数
            'wheresql' => $where, //string //条件SQL语句 
            'orderby' => " ORDER BY mtime DESC ", //string 排序规则
        );
        $page_result = $this->index('trade_refund', $page_condition);        
        //1.课程与内容不符 2.盗版/侵权课程 3.老师授课问题 4.课程质量问题 5.其他
        $reasonArr = self::$reasonArr;
        
        //处理状态：0.待处理 1.已处理 2.已拒绝 3.已关闭
        $statusArr = self::$statusArr;
        
        if(!empty($page_result) && is_array($page_result)){
            //此处将user_id对应换成名称
            foreach($page_result['page_data'] as $k => $item) {
                unset($page_result['page_data'][$k]['tr_tm_id']);
                unset($page_result['page_data'][$k]['tr_tc_id']);
                unset($page_result['page_data'][$k]['tr_user_id']);
                
                $page_result['page_data'][$k]['user_id'] = $item['tr_user_id'];
                $page_result['page_data'][$k]['user_realname'] = ext::user_realname($item['tr_user_id']);
                $page_result['page_data'][$k]['user_name'] = ext::user_name($item['tr_user_id']);
                $page_result['page_data'][$k]['reason_type_key'] = $item['tr_type'];
                $page_result['page_data'][$k]['reason_type'] = $reasonArr[$item['tr_type']];
                $page_result['page_data'][$k]['status'] = $statusArr[$item['tr_status']];
                $page_result['page_data'][$k]['status_key'] = $item['tr_status'];
                
//                $page_result['page_data'][$k]['orderinfo'] = $this->one_info('trade_main', 'tm_id', $item['tr_tm_id']);
//                $page_result['page_data'][$k]['courseinfo'] = @DB::fetch_all("select * from ".DB::table('course_main')." where cm_id in ('".implode("','", json_decode($item['tr_tc_id'], true))."') ");
                $tmp = @DB::fetch_first("select A.cm_id, A.cm_name from ".DB::table('course_main')." as A left join ".DB::table('trade_course')." as B on A.cm_id = B.cm_id where B.tc_id in ('".implode("','", json_decode($item['tr_tc_id'], true))."') "); 
                $page_result['page_data'][$k] += $tmp ? $tmp : ['cm_id' => '', 'cm_name' => '']; 
                
            }
        }
        
        $return['code'] = '0';
        $return['data'] = $page_result;
        $return['data']['page_now'] = $page;
        $return['data']['total_page'] = ceil($return['data']['page_now'] / $limit);
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 单个汇款单订单已收款 API
    */
    public function do_billok(){
        global $_G;
        
        $tm_id = isset($_REQUEST['tm_id']) && !empty($_REQUEST['tm_id']) ? $_REQUEST['tm_id'] : '';
        $is_free = isset($_REQUEST['is_free']) && !empty($_REQUEST['is_free']) ? $_REQUEST['is_free'] : 0;
        
        $return['code'] = '1';
        
        $info = $this->one_info('trade_main', 'tm_id', $tm_id);
        
        //1.获取订单状态 所有未付款状态的订单都可以经过人工收款来处理 处理状态改为 2
        if($info['tm_all_status'] != 1){//订单付款状态为 待付款 才允许操作
            $return['code'] = '2';
        }
        elseif($info['isdelete']){
            $return['code'] = '3';
        }
        else{//此处进行确认该订单操作
            $data = [
                'tm_way' => 2,
                'tm_all_status' => 2, 
                'tm_paytime' => TIMESTAMP
            ];
            
            if($is_free){
                $data['is_free'] = $is_free;
                $data['tm_total_fee'] = 0;//实收金额为0
            }
            //2016-12-16 14:06:43 最新文档已付款状态为2
            $this->edit('trade_course', ['tc_flag' => 2], ['tm_id' => $tm_id]);//将订单内课程的状态改为已付款
            $r = $this->edit('trade_main', $data, ['tm_id' => $tm_id]);
            
            if($r){//成功
                $return['code'] = '0';
                //纳入统计
                $this->toCourseStatistics($tm_id);
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 单个订单已退款 API
    */
    public function do_refundok(){
        global $_G;
        
        $tr_id = isset($_REQUEST['tr_id']) && !empty($_REQUEST['tr_id']) ? $_REQUEST['tr_id'] : '';
        $tr_price_reality = isset($_REQUEST['tr_price_reality']) && !empty($_REQUEST['tr_price_reality']) ? $_REQUEST['tr_price_reality'] : '';
        $tr_refuse_reason = isset($_REQUEST['tr_refuse_reason']) && !empty($_REQUEST['tr_refuse_reason']) ? $_REQUEST['tr_refuse_reason'] : '';
        
        $return['code'] = '1';
        
        $info = $this->one_info('trade_refund', 'tr_id', $tr_id);
        $tm_id = $info['tr_tm_id'];
        $tcIdArr = json_decode($info['tr_tc_id'], true);
        
        //1.获取订单状态
        $detail = $this->one_info('trade_main', 'tm_id', $tm_id);
        if($info['tr_status'] != 1){//订单状态不为退款中不允许删除 或者退款状态不为 待处理
            $return['code'] = '2';
        }
        elseif($detail['isdelete']){
            $return['code'] = '3';
        }
        else{//此处进行删除该订单操作
            
            $r = $this->edit('trade_refund', ['tr_status' => 2, 'mtime' => TIMESTAMP, 'tr_price_reality' => $tr_price_reality, 'tr_refuse_reason' => $tr_refuse_reason], ['tr_id' => $tr_id]);
            
            if($r){//成功
                //此处获取该退款申请的金额
                if($tr_price_reality){
                    $newTotalFee = $detail['tm_total_fee'] - $tr_price_reality;
                }
                else{
                    $newTotalFee = $detail['tm_total_fee'] - $info['tr_price'];
                }
                
                foreach ($tcIdArr as $item) {
                    $this->edit('trade_course', ['tc_type' => 2, 'tc_flag' => 7, 'modify_dateline' => TIMESTAMP], ['tc_id' => $item]);
                    //作废掉对应的订单统计
                    $this->delete('course_statistics', ['cs_tm_id' => $tm_id, 'cs_tc_id' => $item]);
                }
                
                //2016-12-12 14:24:08 此处判断一下是否该主订单下对应的课程都被成功退款，如果都被成功退款的话则订单状态变为 已关闭
                $sql_cnt = "select count(tc.tc_id) from ".DB::table('trade_course')." as tc where 1 = 1 and tc.tc_flag <> 7 and tc.isdelete = 0 and tc.tm_id = ".$tm_id;
                $cnt = DB::result_first($sql_cnt);
                
                if($cnt > 0){//走到这里说明该订单还存在处于非退款状态
                    $this->edit('trade_main', array('tm_all_status' => 2, 'modify_dateline' => TIMESTAMP, 'tm_total_fee' => $newTotalFee), array('tm_id' => $tm_id));
                }
                else{
                    $this->edit('trade_main', array('tm_all_status' => 7, 'modify_dateline' => TIMESTAMP, 'tm_total_fee' => $newTotalFee), array('tm_id' => $tm_id));
                }
                
                $return['code'] = '0';
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 单个订单拒绝退款API
    */
    public function do_refundfail(){
        global $_G;
        
        $tr_id = isset($_REQUEST['tr_id']) && !empty($_REQUEST['tr_id']) ? $_REQUEST['tr_id'] : '';
        $tr_refuse_reason = isset($_REQUEST['tr_refuse_reason']) && !empty($_REQUEST['tr_refuse_reason']) ? $_REQUEST['tr_refuse_reason'] : '';
        
        $return['code'] = '1';
        
        $info = $this->one_info('trade_refund', 'tr_id', $tr_id);
        $tm_id = $info['tr_tm_id'];
        $tcIdArr = json_decode($info['tr_tc_id'], true);
        //1.获取订单状态
        $detail = $this->one_info('trade_main', 'tm_id', $tm_id);
        if($info['tr_status'] != 1){//订单状态不为退款中不允许删除
            $return['code'] = '2';
        }
        elseif($detail['isdelete']){
            $return['code'] = '3';
        }
        else{//此处进行删除该订单操作
            $r = $this->edit('trade_refund', array('tr_status' => 3, 'mtime' => TIMESTAMP, 'tr_refuse_reason' => $tr_refuse_reason), array('tr_id' => $tr_id));
            
            if($r){//成功
                $this->edit('trade_main', array('tm_all_status' => 2, 'modify_dateline' => TIMESTAMP), array('tm_id' => $tm_id));
                
                foreach ($tcIdArr as $item) {
                    $this->edit('trade_course', array('tc_type' => 3, 'tc_flag' => 2, 'modify_dateline' => TIMESTAMP), array('tc_id' => $item));
                }
                
                $return['code'] = '0';
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 单个汇款单详情API
     */
    public function do_billdetail(){
        global $_G;
        
        $tb_trade_id = isset($_REQUEST['trade_id']) && !empty($_REQUEST['trade_id']) ? $_REQUEST['trade_id'] : '';
        
        $return['code'] = '1';//没有对应的汇款单
        
        $info = $this->one_info('trade_bill', 'tb_trade_id', $tb_trade_id);
        
        if(empty($info) || !is_array($info)){//如果结果集为空或者不为数组的话
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        $return['code'] = '0';
        $return['data'] = $info;
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 单个订单详情API
     */
    public function do_detail(){
        global $_G;
        
        $tr_id = isset($_REQUEST['tr_id']) && !empty($_REQUEST['tr_id']) ? $_REQUEST['tr_id'] : '';
        $nowTime = TIMESTAMP;
        
        $return['code'] = '1';
//        $return['data']['order'] = array();
//        $return['data']['course'] = array();
        
        $info = $this->one_info('trade_refund', 'tr_id', $tr_id);
        $tm_id = $info['tr_tm_id'];
        
        if($info){
            $return['code'] = '0';
            
            //1.课程与内容不符 2.盗版/侵权课程 3.老师授课问题 4.课程质量问题 5.其他
            $reasonArr = self::$reasonArr;

            //处理状态：0.待处理 1.已处理 2.已拒绝 3.已关闭
            $statusArr = self::$statusArr;
            
            $info['tm_id'] = $info['tr_tm_id'];
            unset($info['tr_tm_id']);
            $info['user_id'] = $info['tr_user_id'];
            $info['user_name'] = ext::user_realname($info['tr_user_id']);
            unset($info['tr_user_id']);
            $info['reason_type_key'] = $info['tr_type'];
            $info['reason_type'] = $reasonArr[$info['tr_type']];
            $info['status'] = $statusArr[$info['tr_status']];
            $info['status_key'] = $info['tr_status'];
            $info += @DB::fetch_first("select cm_id, cm_name from ".DB::table('course_main')." where cm_id in ('".implode("','", json_decode($info['tr_tc_id'], true))."') ");
            unset($info['tr_tc_id']);
            
            $return['data'] = $info;
        }
        
//        //0.获取该订单详情
//        $detail = $this->one_info('trade_main', 'tm_id', $tm_id);
//        if($detail['modify_dateline']){
//            $detail['tm_success_time'] = date('Y-m-d H:i:s', $detail['modify_dateline']); //支付时间
//        }
//        $detail['tm_all_status'] = $detail['tm_all_status'];
//        $detail['tm_all_status_name'] = mst_trade_status_all($detail['tm_all_status']);
//        $detail['tm_way_name'] = trade_way($detail['tm_way']);
//        
//        $detail_pc = array();
//        $detail_pc['order']['id'] = $detail['tm_id'];
//        $detail_pc['order']['orderId'] = $detail['tm_out_trade_no'];
//        $detail_pc['order']['state'] = $detail['tm_all_status'];
//        $detail_pc['order']['addTime'] = $detail['create_dateline'] ? date('Y-m-d H:i:s', $detail['create_dateline']) : '';
//        $detail_pc['order']['payTime'] = $detail['tm_paytime'] ? date('Y-m-d H:i:s', $detail['tm_paytime']) : '';
//        $detail_pc['order']['create_dateline'] = $detail['create_dateline']; //下单时间
//        
//        //DEBUG 取出订单课程信息 trade_course
//        $sql = "select cm_id from ".DB::table('trade_course')." where tm_id='".$detail['tm_id']."' limit 200";
//        $result = DB::fetch_all($sql);
//        $cm_ids = array();
//        foreach ($result as $v) {
//            $cm_ids[$v['cm_id']] = $v['cm_id'];
//        }
//        
//        $course_info = self::get_field_value_by_id('course_main', 'cm_id', $cm_ids, 'cm_id,cm_name,user_id,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,cm_cate_id,create_dateline');
//        if(!empty($course_info) && is_array($course_info)){
//            foreach ($course_info as $cvalue) {
//                $cvalue['so_name'] = $this->get_field_value_by_id('school_online', 'so_id', $cvalue['so_id'], 'so_name');
//                $detail['tm_trade_course'][] = $cvalue;
//            }
//        }
//        
//        if(!empty($detail['tm_trade_course']) && is_array($detail['tm_trade_course'])){
//            foreach ($detail['tm_trade_course'] as $value) {
//                $tmp = array();
//                $tmp['id'] = $value['cm_id'];
//                $tmp['title'] = $value['cm_name'];
//                $tmp['img'] = $value['cm_img'];
//                $tmp['teacher'] = ext::user_realname($value['user_id']);
//                $tmp['type'] = $value['cm_cate_id'];
//                $tmp['times'] = $value['cm_hour_num'];
//                $tmp['price'] = $value['cm_price'];
//                $detail_pc['course'][] = $tmp;
//            }
//        }
//        
//        $return['data'] = $detail_pc;
//        
//        //如果获取到了订单内容的话说明请求成功
//        if(!empty($return['data']['order']) && is_array($return['data']['order'])){
//            $return['code'] = '0';
//        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 收款列表
     */
    public function do_collection(){
        global $_G;
        
        //此处接收传递的搜索条件
        $user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';//微课号 用户user_id
        $user_name = isset($_REQUEST['user_name']) && !empty($_REQUEST['user_name']) ? $_REQUEST['user_name'] : '';//用户账号
        $user_phone = isset($_REQUEST['user_phone']) && !empty($_REQUEST['user_phone']) ? $_REQUEST['user_phone'] : '';//手机号
        $user_realname = isset($_REQUEST['user_realname']) && !empty($_REQUEST['user_realname']) ? $_REQUEST['user_realname'] : '';//姓名
        $tm_out_trade_no = isset($_REQUEST['tm_out_trade_no']) && !empty($_REQUEST['tm_out_trade_no']) ? $_REQUEST['tm_out_trade_no'] : '';//订单号
        $tm_all_status = isset($_REQUEST['tm_all_status']) && !empty($_REQUEST['tm_all_status']) ? $_REQUEST['tm_all_status'] : '0';//付款状态 2016-11-15 默认返回所有的付款状态
        $tm_way = isset($_REQUEST['tm_way']) && !empty($_REQUEST['tm_way']) ? $_REQUEST['tm_way'] : '0';//支付方式 默认返回所有支付方式
        $orderby = isset($_REQUEST['orderby']) && !empty($_REQUEST['orderby']) ? $_REQUEST['orderby'] : 'desc';//排序方式
        
        $stime = isset($_REQUEST['stime']) && !empty($_REQUEST['stime']) ? $_REQUEST['stime'] : 0;//开始时间
        $etime = isset($_REQUEST['etime']) && !empty($_REQUEST['etime']) ? $_REQUEST['etime'] : 0;//结束时间
        
        $page = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : 15;
        
        $so_id = isset($_REQUEST['so_id']) && !empty($_REQUEST['so_id']) ? $_REQUEST['so_id'] : 0;//网校编号
        
        $start = (($page - 1) * $limit);
        
        $orderStr = " order by tm.create_dateline ".$orderby;
        
        $whereSql = " and tm.is_merge = 0  ";
        
        if($user_id){//如果传递进来了用户的user_id
            $whereSql.= " and tm.user_id = ".$user_id." ";
        }
        
        if($so_id){//如果传递进来了网校编号
            $whereSql.= " and tm.so_id = ".$so_id." ";
        }
        
        if($user_name){//如果传递进来了用户的用户名
            $whereSql.= " and u.user_name = '".$user_name."' ";
        }
        
        if($user_phone){//如果传递进来了用户的手机号
            $whereSql.= " and ud.user_phone = '".$user_phone."' ";
        }
        
        if($user_realname){//如果传递进来了用户的真实名称
            $whereSql.= " and ud.user_realname = '".$user_realname."' ";
        }
        
        if($tm_out_trade_no){//如果传递进来了订单号
            $whereSql.= " and tm.tm_out_trade_no = '".$tm_out_trade_no."' ";
        }
        
        if($tm_all_status){//如果传递进来了付款状态
            $whereSql.= " and tm.tm_all_status = '".$tm_all_status."' ";
        }
        
        if($tm_way){//如果传递进来了支付方式
            $whereSql.= " and tm.tm_way = '".$tm_way."' ";
        }
        
         if($stime){//开始时间
            $whereSql.= " and tm.create_dateline >= '".$stime."' ";
        }
        
        if($etime){//结束时间
            $whereSql.= " and tm.create_dateline <= '".$etime."' ";
        }
        
        $sql = "select tm.*, u.user_id, u.user_name, ud.user_phone, ud.user_realname from ".DB::table('trade_main')." as tm "
                . " left join ".DB::table('user')." as u on u.user_id = tm.user_id "
                . " left join ".DB::table('user_detail')." as ud on ud.user_id = u.user_id where 1 = 1 ".$whereSql." ".$orderStr." ".DB::limit($start, $limit);
        
        $sql_result = DB::fetch_all($sql);
        
        $sql_total_rows = "select count(tm.tm_id) from ".DB::table('trade_main')." as tm "
                . " left join ".DB::table('user')." as u on u.user_id = tm.user_id "
                . " left join ".DB::table('user_detail')." as ud on ud.user_id = u.user_id where 1 = 1 ".$whereSql;
        
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        
        //DEBUG 列表数据返回结构
        $page_result = array(
            'page_now' => $page,
            'total_page' => max(1, ceil($sql_total_rows_result / $limit)),
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_result
        );
        
        $return['code'] = '0';
        $return['data'] = $page_result;
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 收款结果集导出
     */
    public function do_export(){
        global $_G;
        //此处接收传递的搜索条件
        $user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';//微课号 用户user_id
        $user_name = isset($_REQUEST['user_name']) && !empty($_REQUEST['user_name']) ? $_REQUEST['user_name'] : '';//用户账号
        $user_phone = isset($_REQUEST['user_phone']) && !empty($_REQUEST['user_phone']) ? $_REQUEST['user_phone'] : '';//手机号
        $user_realname = isset($_REQUEST['user_realname']) && !empty($_REQUEST['user_realname']) ? $_REQUEST['user_realname'] : '';//姓名
        $tm_out_trade_no = isset($_REQUEST['tm_out_trade_no']) && !empty($_REQUEST['tm_out_trade_no']) ? $_REQUEST['tm_out_trade_no'] : '';//订单号
        $tm_all_status = isset($_REQUEST['tm_all_status']) && !empty($_REQUEST['tm_all_status']) ? $_REQUEST['tm_all_status'] : '1';//付款状态
        $tm_way = isset($_REQUEST['tm_way']) && !empty($_REQUEST['tm_way']) ? $_REQUEST['tm_way'] : '0';//支付方式
        $orderby = isset($_REQUEST['orderby']) && !empty($_REQUEST['orderby']) ? $_REQUEST['orderby'] : 'desc';//排序方式
        $cm_cate_id = isset($_REQUEST['cm_cate_id']) && !empty($_REQUEST['cm_cate_id']) ? $_REQUEST['cm_cate_id'] : '';//课程分类
        
        $so_id = isset($_REQUEST['so_id']) && !empty($_REQUEST['so_id']) ? $_REQUEST['so_id'] : 0;//网校编号
        
        $stime = isset($_REQUEST['stime']) && !empty($_REQUEST['stime']) ? $_REQUEST['stime'] : 0;//开始时间
        $etime = isset($_REQUEST['etime']) && !empty($_REQUEST['etime']) ? $_REQUEST['etime'] : 0;//结束时间
        
        $orderStr = " order by tm.create_dateline ".$orderby;
        
        $whereSql = " and tm.is_merge = 0  ";
        
        if($user_id){//如果传递进来了用户的user_id
            $whereSql.= " and tm.user_id = ".$user_id." ";
        }
        
        if($so_id){//如果传递进来了网校编号
            $whereSql.= " and tm.so_id = ".$so_id." ";
        }
        
        if($user_name){//如果传递进来了用户的用户名
            $whereSql.= " and u.user_name = '".$user_name."' ";
        }
        
        if($user_phone){//如果传递进来了用户的手机号
            $whereSql.= " and ud.user_phone = '".$user_phone."' ";
        }
        
        if($user_realname){//如果传递进来了用户的真实名称
            $whereSql.= " and ud.user_realname = '".$user_realname."' ";
        }
        
        if($tm_out_trade_no){//如果传递进来了订单号
            $whereSql.= " and tm.tm_out_trade_no = '".$tm_out_trade_no."' ";
        }
        
        if($tm_all_status){//如果传递进来了付款状态
            $whereSql.= " and tm.tm_all_status = '".$tm_all_status."' ";
        }
        
        if($tm_way){//如果传递进来了支付方式
            $whereSql.= " and tm.tm_way = '".$tm_way."' ";
        }
        
        if($cm_cate_id){//如果传递进来了课程分类
            $whereSql.= " and cm.cm_cate_id = '".$cm_cate_id."' ";
        }
        
        if($stime){//开始时间
            $whereSql.= " and tm.create_dateline >= '".$stime."' ";
        }
        
        if($etime){//结束时间
            $whereSql.= " and tm.create_dateline <= '".$etime."' ";
        }
        
        $sql = "select tm.*, u.user_id, u.user_name, ud.user_phone, ud.user_realname, cm.cm_cate_id, cc.cc_name, cm.cm_price from ".DB::table('trade_main')." as tm "
                . " left join ".DB::table('trade_course')." as tc on tc.tm_id = tm.tm_id "
                . " left join ".DB::table('course_main')." as cm on cm.cm_id = tc.cm_id "
                . " left join ".DB::table('user')." as u on u.user_id = tm.user_id "
                . " left join ".DB::table('course_cate')." as cc on cc.cc_id = cm.cm_cate_id "
                . " left join ".DB::table('user_detail')." as ud on ud.user_id = u.user_id where 1 = 1 ".$whereSql." ".$orderStr;
        
        $sql_result = DB::fetch_all($sql);
        
        $statusArr = array(
            1 => '待付款',
            2 => '已付款',
            3 => '已成功',
            4 => '待评价',
            5 => '退款中',
            6 => '已评价',
            7 => '已关闭',
        );
        
        //开始组装目标数组
        $filename = 'zfgl'.date('YmdHis').'.csv'; //设置文件名
        $f = ',';//定义分隔符
        $list[] = iconv("utf-8","gb2312",'微课号'.$f.'账号'.$f.'手机号'.$f.'姓名'.$f.'课程名称'.$f.'课程价格'.$f.'选课时间'.$f.'订单号'.$f.'订单状态');

        //将上述结果集转换为目标数组
        if(!empty($sql_result) && is_array($sql_result)){
            foreach ($sql_result as $item) {
                $list[] = iconv("utf-8","gb2312",$item['user_id'].$f.$item['user_name'].$f.$item['user_phone'].$f.$item['user_realname'].$f.$item['cc_name'].$f.$item['cm_price'].$f.date('Y-m-d H:i:s', $item['create_dateline']).$f.$item['tm_out_trade_no'].$f.$statusArr[$item['tm_all_status']]);
            }
        }
        
        $target = SITE_ROOT.'data/upload/';
        $fp = fopen($target.$filename, 'w');
        //向目标文件写入操作
        foreach ($list as $line) {
            fputcsv($fp, explode(',', $line));
        }

        fclose($fp);
        
        $return['code'] = '1';
        //检测是否对应已生成csv文件
        if(is_file($target.$filename)){
            //2017-6-6 11:51:34 此处将该csv文件上传到文件服务器，同时删除本地的文件
            $data = ['filedata'  =>  new CURLFile($target.$filename), 'dir' => '/'];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
            curl_setopt($ch, CURLOPT_POST, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

             $res = curl_exec($ch);
             curl_close($ch);

             //此处删除掉本地的文件
             @unlink($target.$filename);

             if($res == 'success'){//成功
                $return['code'] = '0';
                $return['data']['url'] = 'http://fstore.jxzhjy.com/data/upload/'.$filename;
             }
             else{//远程文件上传失败
                $return['code'] = '1';
                $return['data']= [];
             }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 传入user_id和cm_id删除对应用户的选课
    */
    public function do_coursedel(){
        global $_G;
        
        $user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;//要被选课的学生id
        $cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : 0;//传递过来的课程id数组
        
        //如果没有传递进来用户和课程的话为失败！
        if(!$user_id || !$cm_id){
            $return['code'] = '2';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        $sql = "select tm.tm_id from ".DB::table('trade_main')." as tm "
                . " left join ".DB::table('trade_course')." as tc on tc.tm_id = tm.tm_id "
                . " where tc.user_id = ".$user_id." and tc.cm_id = ".$cm_id." and tc.tc_flag = 2 and tc.tc_type = 0 ";
        
        $sql_result = DB::fetch_all($sql);
        
        $tmIdArr = [];
        if(!empty($sql_result) && is_array($sql_result)){
            foreach($sql_result as $item){
                $tmIdArr[] = $item['tm_id'];
            }
        }
        
        $return['code'] = '1';
        
        $r = $this->edit('trade_course', ['tc_flag' => 8, 'modify_dateline' => TIMESTAMP], ['user_id' => $user_id, 'cm_id' => $cm_id, 'tc_flag' => 2, 'tc_type' => 0]);
        
        if($r){//删除成功
            $return['code'] = '0';
            
            if(!empty($tmIdArr) && is_array($tmIdArr)){
                foreach($tmIdArr as $one) {
                    $tm_id = $one;
                    $sql_cnt = "select count(tc.tc_id) from ".DB::table('trade_course')." as tc where 1 = 1 and tc.tc_flag <> 8 and tc.tm_id = ".$tm_id;
                    $cnt = DB::result_first($sql_cnt);

                    if($cnt == 0){//说明全部都已处于删除状态，更新订单状态为已删除
                        $this->edit('trade_main', ['tm_all_status' => 8, 'modify_dateline' => TIMESTAMP], ['tm_id' => $tm_id]);
                    }
                }
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 指定学生选课 API
     */
    public function do_course(){
        global $_G;
        
        $user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;//要被选课的学生id
        $cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';//传递过来的课程id数组
        $isFree = isset($_REQUEST['is_free']) && !empty($_REQUEST['is_free']) ? $_REQUEST['is_free'] : 0;//是否免费
        
        //如果没有传递进来用户和课程的话为失败！
        if(!$user_id){
            $return['code'] = '2';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        $is_success = false;
        //如果选择的课程编号不为空继续
        if(!empty($cm_id) && is_array($cm_id)){
            $c_user_id = $user_id;
            $c_tm_out_trade_no = '0512'.date('YmdHis').rand(1000, 9999);
            $c_status = 'TRADE_SUCCESS';
            $c_time = TIMESTAMP;
            
            //2016-12-21 09:24:43 对传递过来的cm_id数组进行网校判断
            $soArr = [];//网校集合
            if(!empty($cm_id) && is_array($cm_id)){
                foreach($cm_id as $item){
                    $soIdTmp = $this->cmIdToSoId($item);
                    $soArr[$soIdTmp]['cmId'][] = $item;
                }
            }
            
            $soCnt = count($soArr);
            //主订单创建
            //如果此时的网校集合内网校数量大于1的话说明该订单将会是一张混合订单，需要进行拆分订单处理
            if($soCnt > 1){
                //此处进行子订单的生成
                foreach($soArr as $k => $v){
                    $so_id = sprintf("%08d", $k);
                    $tm_id = $this->newTrade($v['cmId'], $c_user_id, $c_tm_out_trade_no.$so_id, $c_status, $c_time, 0, 0, $isFree, true);
                    $this->toCourseStatistics($tm_id);
                }
            }
            else{//只有一张订单不需要拆分此处加入网校so_id
                $tm_id = $this->newTrade($cm_id, $c_user_id, $c_tm_out_trade_no, $c_status, $c_time, 0, 0, $isFree, true);
                $this->toCourseStatistics($tm_id);
            }
            
            $is_success = true;
        }
        else{
            $return['code'] = '2';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }

        if($is_success){
            $return['code'] = '0';
        }
        else{
            $return['code'] = '1';
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * csv批量选课
     */
    public function do_coursecsv(){
        global $_G;
        
        @set_time_limit(0);
        @set_magic_quotes_runtime(0);
        @ini_set('memory_limit','2048M');
        //接收参数
        $filepath = isset($_REQUEST['filepath']) && !empty($_REQUEST['filepath']) ? $_REQUEST['filepath'] : '';//上传的csv路径
        if(!$filepath){//如果没有传递过来对应的参数路径
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        //读取csv内容
        $handle = fopen($filepath, 'r'); 

        $result = array();
        $n = 0;
        while($data = fgetcsv($handle, 10000)){
            $num = count($data);
            for ($i = 0;$i < $num;$i++) {
                $result[$n][$i] = iconv('gb2312', 'utf-8', $data[$i]);
            }
            $n++;
        }

        fclose($handle); //关闭指针
        
        $len_result = count($result);
        if($len_result <= 1){
            $return['code'] = '2';//没有数据
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        unset($result[0]);
        
        //遍历结果集
        foreach ($result as $item) {
            //根据传递过来的用户名找到对应的user_id
            $user_id = ext::get_user_id($item[0]);
            //订单状态
            $flag = $item[2];
            //是否免费
            $isFree = $item[3];
            //选课编号
            $cmArr = array();
            if($user_id && $item[1] && in_array($flag, array(1, 2)) && in_array($isFree, array(0, 1))){//该下标数据不为空 并且状态信息符合要求
                $cmArr = explode(';', $item[1]);
                //如果选择的课程编号不为空继续
                if(!empty($cmArr) && is_array($cmArr)){
                    //此处开始预生成总订单
                    $tradeMain = array();
                    
                    $tradeMain['user_id'] = $user_id;//用户编号
                    $tradeMain['tm_out_trade_no'] = '0512'.date('YmdHis').rand(1000, 9999);//网校订单号
                    $tradeMain['tm_youhui'] = '0.00';
                    $tradeMain['tm_total_price'] = '0.00';//原价
                    $tradeMain['tm_total_fee'] = '0.00';//付款金额
                    
                    foreach($cmArr as $one){
                        //获取课程的价格
                        $cm_price = ext::get_cm_info($one, 'cm_price');
                        $tradeMain['tm_total_price'] += $cm_price;
                        if(!$isFree){//如果不是免费用户的话需要付费
                            $tradeMain['tm_total_fee'] += $cm_price;
                        }
                    }
                    
                    $tradeMain['tm_way'] = '2';//收款方式 2016-11-17 所有导入方式的数据支付方式都是人工收款
                    if($flag == 2){//已付款 -- 人工收款
                        $tradeMain['tm_paytime'] = TIMESTAMP;//付款时间
                    }
                    
                    $tradeMain['create_dateline'] = $tradeMain['modify_dateline'] = TIMESTAMP;
                    
                    if($isFree){
                        $tradeMain['is_free'] = 1;//是否免费
                    }
                    
                    $tradeMain['tm_all_status'] = $flag;//订单状态
                    
                    $tm_id = $this->add('trade_main', $tradeMain, true);
                    //此时向订单商品表中添加数据
                    foreach($cmArr as $one){
                        //获取课程的价格
                        $cm_price = ext::get_cm_info($one, 'cm_price');
                        $cnt = ext::get_cm_info($one, 'cm_count');
                        
                        $data = array(
                            'user_id'   => $user_id,
                            'cm_id'     => $one,
                            'cm_price'  => $cm_price,
                            'tc_flag'   => $flag == 2 ? 2 : 1,
                            'tm_id'     => $tm_id,
                            'create_dateline' => TIMESTAMP,
                            'modify_dateline' => TIMESTAMP
                        );
                        @DB::insert('trade_course', $data, true);
                        @DB::update('course_main', ['cm_count' => $cnt + 1], ['cm_id' => $one]);
                    }
                }
            }
            
            //此时如果是已付款订单或者免费订单的话需要加入到统计中去
            if(($flag == 2) || $isFree){
                $this->toCourseStatistics($tm_id);
            }
            
        }
        
        $return['code'] = '0';
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /**
    * 订单主表数据修复脚本
    * php admin/cli.php -m trade -a main -d traderepair
    */
    public function do_traderepair(){
        global $_G;
        @set_time_limit(0);
        @set_magic_quotes_runtime(0);
        @ini_set('memory_limit', '2048M');
        //DEBUG 导入 开始
        //连接老数据库
        $driver = 'db_driver_mysql';
        DB::init($driver, $_G['config']['old_db']);
        //DEBUG 获取用户表数据
        $old_table = 'trade_diff_info';
        $new_table = 'trade_diff_info';

        // MARK: 以订单主表作为扫描对象
        $start = 0;
        // 定义步长
        $stepSize = 5000;
        // 获取 旧表 数据总数
        $sql_cnt_old = "select count(*) as cnt from ".DB::table($old_table)." where isdelete = 0 ";
        $result_count = $count_old = DB::result_first($sql_cnt_old);//旧数据条数
        $import_count = 0;//成功导入的条数

        while($count_old > 0){//如果还有尚未处理的数据
            DB::init($driver, $_G['config']['old_db']);//切换数据库连接句柄到旧库
            // 按照步长吞入内存数据
            $resArr = [];//定义接收结果池

            $sql_res = "select * "
                    . " from ".DB::table($old_table)
                    . " where isdelete = 0 "
                    . " limit ".$start.", ".$stepSize;
            $resArr = DB::fetch_all($sql_res);

            //连接新数据库
            DB::init($driver, $_G['config']['db']);
            if(!empty($resArr) && is_array($resArr)){
                foreach ($resArr as $item) {//遍历目标结果集重新组装数据
                    $data = [
                        'tdi_id'             =>  $item['tdi_id'],
                        'user_id'            =>  $item['user_id'],
                        'tdi_price'          =>  $item['tdi_price'],
                        'tm_id'              =>  $item['trade_id'],
                        'tm_out_trade_no'    =>  $item['out_trade_no'],
                        'create_dateline'    =>  $item['create_dateline'],
                        'modify_dateline'    =>  $item['modify_dateline']
                    ];

                    $insert_id = DB::insert($new_table, $data, true, true);
                    if($insert_id){
                        $import_count += 1;
                    }
                }
            }

            $start += $stepSize;//数据查询偏移量为步长
            $count_old -= $stepSize;//待处理数据量减少为步长

            sleep(1);//程序休息1秒
        }

        $log .= 'get total '.$old_table.' = '.$result_count.PHP_EOL;
        $log .= 'import total count = '.$import_count.PHP_EOL;
        $import_status='failed';
        if($import_count==$result_count){
            $import_status='success';
        }
        $log .= 'import '.$new_table.' table '.$import_status.PHP_EOL;
        echo '程序执行完毕！\n'.$log;
        return false;
    }
    
}